<?php

namespace common\helpers;

use yii;



/**
 * Class ModelHelper
 * @package common\helpers
 * @author zyesd  email:809807519@qq.com
 */
class ModelHelper
{



    /**
     * 将二位数组附加转换字段,如表中只有created_id,但输出需要带上姓名
     * @param array $basicData :  原始数据,一般为查询后得到的二维数组
     * @param array $args : 输入字段及值,如 ['user_id'=>[1,3,5]]
     * @return array  返回加工后的二维数组
     */
    /* 
        args:参数
        [
            [
              
              'inputFields'=>['inputField1','inputField2'], //要转化的字段,可能多个字段去对应表中一个字段,如创建者和修改者的id都是在admin表中的user_id字段里
              'class'=>'', //处理对应的类名,使用全路径,如'\common\models\Admin'
              'outFields'=>['outField1','outField2'], //表中找到对应信息后,要保留的字段名              
              'keyField'=>'keyFieldName' ,  ////表关键对应字段,一般为表主键,如'user_id'
              //输出时相应的对应信息,输入字段(inputField)对应什么输出字段(toField'),输出的名称是什么(outName) 
              'relation'=>[
                    'inputField1'=>['toField'=>'outField1','outName'=>'outName1'],
                    'inputField2'=>['toField'=>'outField2','outName'=>'outName1'],
                    ],
              'name'=>'name' //名称,用于区别其他要转化的字段      
            ],
            //exmple
            [
                'inputFields'=>['created_id','updated_id'],
                'class'=>'\common\models\Admin',
                'outFields'=>['user_id','username','real_name'], 
                'keyField'=>'user_id', 
                'relation'=>[
                    'created_id'=>['toField'=>'username','outName'=>'creater'],
                    'updated_id'=>['toField'=>'username','outName'=>'updater'],
                    ],
                'name'=>'idToUser'
            ]            
        ]    
    */
    public static function attachFieldsValue($basicData, $args = [])
    {
        //判断$basicData是否为二维数组,是否为空,符合条件则准备转化

        //判断$args是否为二维数组,是否为空,符合条件则准备转化

        $dataOld = $basicData;

        $data = [];

        $arrRelationData = []; //找到的对应数据保存在此变量
        foreach ($args as $key => $value) {
            if (array_key_exists('class', $value)) {

                //获取需要转化的字段数据(为二维数组),返回需要转化的列,为一维数组,并去重,结果如[1,3,5]
                //$arrInputFieldValue = array_unique(array_column($dataOld,$value['inputField'][0]));
                $arrTemp = [];
                foreach ($value['inputFields'] as $item) {
                    $arrTemp = array_merge($arrTemp, array_column($dataOld, $item));
                }
                //结果如[1,3,5]
                $arrInputFieldValue = array_unique($arrTemp);

                //$value['inputField']
                //找到要转换的对应数据,返回二位数组,如[ ['created_id'=>1,'name'=>'admin'] , ['created_id'=>3,'name'=>'test']  ]
                $arrFields = self::findModelByFieldValue($value['class'], [$value['keyField'] => $arrInputFieldValue], $value['outFields']);


                //对应整理找到的数据,返回如['10007'=>['admin','10007'],'10026'=>['test','10026']]
                $result = array_column($arrFields, null, $value['keyField']);

                //返回如:['idToUser'=>['10007'=>['username'=>'admin'],'10026'=>['username'=>'test']]]
                $arrRelationData[$value['name']] = $result;
            }
        }


        //重组数据,加入添加者和修改者姓名内容
        foreach ($dataOld as $key => $value) {
            //复制原数据
            $data[$key] = $value;
            //附加数据
            //遍历$args中的relation,增加字段 
            foreach ($args as $item) {
                foreach ($item['relation'] as $k => $v) {
                    //$arrRelationData[$item['name']]中查找是否有对应数据,有则取值
                    //$value[$k]为原始数据中相应字段的值,$k为字段名,这儿为$value['created_id']='10007'
                    if (array_key_exists($value[$k], $arrRelationData[$item['name']])) {
                        /* 
                        $data[$key][$v['outName']] = $data[0]['creater'] 
                        $key 为原数据当前行的行标,如0, $v['outName'] 为新加的字段的名

                        $arrRelationData[$item['name']][$value[$k]][$v['toField']]=$arrRelationData['idToUser']['10007']['username']
                        $item['name']为对应的$args['name']
                        $value[$k]为原始数据中相应字段的值,$k为字段名,这儿为$value['created_id']='10007'
                        */

                        $data[$key][$v['outName']] = $arrRelationData[$item['name']][$value[$k]][$v['toField']];
                    }
                }
            }
        }
        return $data;
    }



    /**
     * 在表中根据 输入字段及值作为条件查找,根据输出字段进行输出
     * @param string $tableClassName :  如'\common\models\Admin'
     * @param array $inputField : 输入字段及值,如 ['user_id'=>[1,3,5]]
     * @param array $outFields :  输出字段 如 ['user_id','username','real_name']
     * @return array  返回二位数组
     */
    public static function findModelByFieldValue($tableClassName, $inputField = [], $outFields = [])
    {
        $arrModel = [];
        $arrOutFields = [];
        if (!empty($outFields)) {

            $arrOutFields = implode(',', $outFields);
        }

        $arrInputField = [];
        if (!empty($inputField)) {
            $arrInputField = $inputField;
        }

        //$table = $tableName::class();
        //’id’ => [1, 2, 3],
        //['user_id'=>['100007','100025']]
        $arrModel = $tableClassName::find()->select($arrOutFields)->where($arrInputField)->asArray()->all();

        if ($arrModel == null) {
            $arrModel = [];
        }


        return $arrModel;

        /* if ($arrModel !== null) {
            return $arrModel;
        }
        
        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.')); */
    }




    // 日志表名称
    const DB_TABLE_LOG = 'config_dblog';
    /**
     * 插入操作.
     * @param obj $event
     * @return mixed
     */
    public static function afterInsert($event)
    { 
        //die("123");
        if($event->sender->tableName() != self::DB_TABLE_LOG){
            // 内容
            $arr = [];
            foreach($event->sender as $key => $value) { 
                $arr[$key] = $value; 
            } 
            $description = json_encode($arr);

            // IP转换
            $ip = Yii::$app->request->userIP;;
            //$ip = ip2long($ip);

            // 保存
            $data = [ 
                /* 'route' => Url::to(), 
                'table' => $event->sender->tableName(),
                'class' => $event->sender->className(), 
                'type' => 1, 
                'description' => $description, 
                'user_id' => Yii::$app->user->id, 
                'create_time' => time(),  */
                'user_id' => Yii::$app->user->id, 
                'ip' => $ip
            ]; 
            $model = new \common\models\log\ConfigDblog(); 
            $model->setAttributes($data); 
            $model->save(false); 
        }
    } 































}
